﻿using System;
using System.Collections;
using System.Diagnostics;
using System.IO;
using System.Text;

namespace winfrom_nested_chromium_75 {
  class PropertiesConfig {
    private static Hashtable _ht = new Hashtable(16);
    static PropertiesConfig() {
      var ht = new Hashtable();
      string file = @"app.properties";
      if (!File.Exists(file)) { 
        //将变量列入到配置文件中
        _ht=initProperties();
        save(file,_ht);
      } else {
        //加载配置文件,验证配置文件,保存配置文件
        _ht = load(file);
        if (validate()) {
          save(file, _ht);
        }
      }
    }

    private static Hashtable initProperties() {
      _ht["project.name"] = "合光机器人知识库";
      _ht["manager.url"] = "http://ibotcluster.online.uairobot.com/manager";
      return _ht;
    }
    
    private static bool validate() {
      var retval = false;
      if (_ht["project.name"] == null) {
        _ht["project.name"] = "合光机器人知识库";
        retval = true;
      }
      if (_ht["manager.url"] == null) {
        _ht["manager.url"] = "http://ibotcluster.online.uairobot.com/manager";
        retval = true;
      }
      return retval;
    }
    public static Hashtable load(string file) {
      string content = null;
      var ht = new Hashtable();
      try {
        content = File.ReadAllText(file, System.Text.Encoding.UTF8);
      } catch (Exception e) {
        return null;
      }
      string[] rows = content.Split('\n');
      string[] kv = null;
      foreach (string c in rows) {
        if (c.Trim().Length == 0)
          continue;
        kv = c.Split('=');
        if (kv.Length == 1) {
          ht[kv[0].Trim()] = "";
        } else if (kv.Length == 2) {
          ht[kv[0].Trim()] = kv[1].Trim();
        }
      }
      return ht;
    }

    public static bool save(string file, Hashtable ht) {
      if (ht == null || ht.Count == 0)
        return false;
      StringBuilder sb = new StringBuilder(ht.Count * 12);
      foreach (string k in ht.Keys) {
        sb.Append(k).Append('=').Append(ht[k]).Append(System.Environment.NewLine);
      }
      try {
        File.WriteAllText(file, sb.ToString(), System.Text.Encoding.UTF8);
        return true;
      } catch (Exception e) {
        return false;
      }
    }

    public static string getValue(string key) {
      return (string)_ht[key];
    }
  }
}
